package net.schastny.shopmanager;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LayoutInterceptor extends HandlerInterceptorAdapter {
	   private static final String NO_LAYOUT = "noLayout:";

	   private String layoutView;

	   @Override
	   public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	       super.postHandle(request, response, handler, modelAndView);

	       String originalView = modelAndView.getViewName();
	       System.out.println("-------------postHandle"+originalView);	      
	       if (originalView != null && !originalView.startsWith("redirect:")) {
	           includeLayout(modelAndView, originalView);
	       }
	   }
	   
	   @Override
	   public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler)   throws Exception{
		    System.out.println("-------------preHandle");	      
		   return true;
		   
	   }

	   private void includeLayout(ModelAndView modelAndView, String originalView) {
	       boolean noLayout = originalView.startsWith(NO_LAYOUT);

	       String realViewName = (noLayout) ? originalView.substring(NO_LAYOUT.length()) : originalView;
	       System.out.println("-------------includeLayout"+originalView);
	       if (noLayout) {
	           modelAndView.setViewName(realViewName);
	       } else {
	           modelAndView.addObject("view", realViewName);
	           modelAndView.setViewName(layoutView);
	       }
	   }

	   public void setLayoutView(String layoutView) {
	       System.out.println("-------------setLayoutView"+layoutView);
	       this.layoutView = layoutView;
	   }
	}